package com.ra.brand;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.espirit.eap.manager.DictionaryService;
import com.espirit.eap.manager.TaskSchedulerService;
import com.espirit.eap.util.Functions;
import com.espirit.eap.util.ImageUtils;
import com.googlecode.cswish.Config;
import com.googlecode.cswish.annotation.Rest;
import com.googlecode.cswish.struts.ServletRedirectResult;
import com.googlecode.cswish.struts.spring.GenericService;
import com.googlecode.cswish.struts.spring.ObjectFactory;
import com.opensymphony.xwork2.Result;
import com.ra.external.BuildingInfoService;
import com.ra.external.RoomInfoService;
import com.ra.landlord.Building;
import com.ra.landlord.BuildingService;
import com.ra.landlord.LandlordOwnerUser;
import com.ra.landlord.LandlordUser;
import com.ra.landlord.LandlordUserService;

/**
 * 品牌公寓服务
 * 
 * @author colin
 * 
 */
@Service
public class BrandApartmentService {

	private static final Log logger = LogFactory.getLog(BrandApartmentService.class);

	@Resource
	private GenericService genericService;

	@Resource
	private LandlordUserService landlordUserService;
	
	@Resource
	private Functions functions;
	
	@Resource
	private ObjectFactory objectFactory;
	
	@Resource
	private BuildingService buildingService;
	
	@Resource
	private BuildingInfoService buildingInfoService;
	
	@Resource
	private RoomInfoService roomInfoService;
	
	@Resource
	private DictionaryService dictionaryService;
	
	@Resource
	private TaskSchedulerService taskSchedulerService;
	
	/**
	 * 增加一个品牌公寓
	 * 
	 * @param model
	 * @return
	 */
	public Result brandApartmentSubmit(BrandApartment model) {
		LandlordOwnerUser landlordOwnerUser = landlordUserService
				.getLandlordOwnerUser();
		LandlordUser landlordUser = landlordUserService.getLandlordUser();
		model.setLandlordUser(landlordOwnerUser);
		model.setCreateUser(landlordUser);
		
		Result result = new ServletRedirectResult(functions.getSite()
				+ "/ra/brand/brandApartment.apply.html");
		objectFactory.autoWireBean(result);
		if(model.getId() != null) {
			this.updateBrandApartment(model);
			return result;
		}
		
		// 处理PC或手机Banner
		this.getBrandApartmentBanner(model);
		
		// 处理推荐房源
//		List<BrandPromotehouse> removeHouses = new ArrayList<BrandPromotehouse>();
//		for(BrandPromotehouse house : model.getBrandPromotehouses()) {
//			if(house.getHouseId() == null) {
//				removeHouses.add(house);
//			}
//		}
//		model.getBrandPromotehouses().removeAll(removeHouses);
		
		//需要初始化一个排名分数，根据房东是否认证，资料完善度，目前只初始化一个固定值100；
		model.setScore(100);
		model.setStatus(BrandApartment.STATUS_AUDITING);
		model.setCreateTime(Calendar.getInstance().getTime());
		genericService.add(model);
		return result;
	}
	
	/**
	 * 处理PC或手机Banner
	 * @param model
	 */
	private void getBrandApartmentBanner(BrandApartment model) {
		List<BrandApartmentBanner> brandApartmentBannersPc = model.getBrandApartmentBannersPc();
		List<BrandApartmentBanner> brandApartmentBannersPhone = model.getBrandApartmentBannersPhone();
		
		List<BrandApartmentBanner> brandApartmentBanners = new ArrayList<BrandApartmentBanner>();
		if(CollectionUtils.isNotEmpty(brandApartmentBannersPc)) {
			for(BrandApartmentBanner bannerPc : brandApartmentBannersPc) {
				bannerPc.setType(BrandApartment.BANNER_PC);
			}
			brandApartmentBanners.addAll(brandApartmentBannersPc);
		}
		
		if(CollectionUtils.isNotEmpty(brandApartmentBannersPhone)) {
			for(BrandApartmentBanner bannerPhone : brandApartmentBannersPhone) {
				bannerPhone.setType(BrandApartment.BANNER_PHONE);
			}
			brandApartmentBanners.addAll(brandApartmentBannersPhone);
		}
		model.setBrandApartmentBanners(brandApartmentBanners);
	}
	
	/**
	 * 更新品牌公寓
	 * @return BrandApartment
	 */
	private BrandApartment updateBrandApartment(BrandApartment model) {
		this.getBrandApartmentBanner(model);
		Collection<String> enableFields = Arrays.asList("baName", "baIcon", "baIconFileName", "brandApartmentBanners", "baCharactServiceItem", "brandPromotehouses"
				, "brandApartmentIntroducePics");
		// 处理推荐房源
//		List<BrandPromotehouse> removeHouses = new ArrayList<BrandPromotehouse>();
//		for(BrandPromotehouse house : model.getBrandPromotehouses()) {
//			if(house.getHouseId() == null) {
//				removeHouses.add(house);
//			} 
//		}
//		model.getBrandPromotehouses().removeAll(removeHouses);
		model.setStatus(BrandApartment.STATUS_AUDITING);
		return genericService.update(model, false, enableFields, null);
	}

	/**
	 * 按积分（由高至低）查询已审核的品牌公寓
	 * 
	 * @param model
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 */
	@Rest(simpleServiceName = "anonymity", type = "free")
	public List<BrandApartment> searchAuditedBrandApartments(BrandApartment model, Integer pageIndex, Integer pageSize) {

		if (pageIndex == null || pageIndex < 1) {
			pageIndex = 1;
		}
		if (pageSize == null || pageIndex < 1) {
			pageSize = 6;
		}
		model.setStatus(BrandApartment.STATUS_AUDITED);
		String strShort = "score"; 
		String strOrderBy = "DESC";
		List<BrandApartment> brandApartments = this.genericService.search(model, (pageIndex - 1) * pageSize, pageSize, strShort, strOrderBy, false, null, null, true, true).getData();
		
		List<BrandApartment> result = new ArrayList<>();
		List<BrandApartment> noPublishRoomApartment = new ArrayList<>();
		
		for (BrandApartment brandApartment : brandApartments) {
			if (brandApartment.getPublishRoomNum() == null || brandApartment.getPublishRoomNum().equals(0)) {
				noPublishRoomApartment.add(brandApartment);
			}else{
				result.add(brandApartment);
			}
		}
		
		result.addAll(noPublishRoomApartment);
		
		return result;
	}

	/**
	 * 查询指定品牌公寓ID的详细信息
	 * 
	 * @param baId
	 * @return
	 */
	@Rest(type = "search")
	public BrandApartment getBrandApartment(Integer baId) {
		return this.genericService.load(BrandApartment.class, baId);
	}
	
	// 根据当前登录房东查询品牌公寓
	public BrandApartment apply() {
		LandlordOwnerUser landlordOwnerUser = landlordUserService
				.getLandlordOwnerUser();
		BrandApartment queryModel = new BrandApartment();
		queryModel.setLandlordUser(landlordOwnerUser);
		
		BrandApartment result = genericService.searchAll(queryModel).getData(0);
		if(result == null) {
			result = new BrandApartment();
		}
		
		// 设置集中式楼房列表信息
		List<Building> buildings = buildingService.searchBuilding();
		if(CollectionUtils.isNotEmpty(buildings)) {
			result.setBuildings(buildings);
		}
		return result;
	}

	// 根据当前登录房东查询品牌公寓
	public BrandApartment index() {
		LandlordOwnerUser landlordOwnerUser = landlordUserService
				.getLandlordOwnerUser();
		BrandApartment queryModel = new BrandApartment();
		queryModel.setLandlordUser(landlordOwnerUser);
		
		BrandApartment result = genericService.searchAll(queryModel).getData(0);
		if(result == null) {
			result = new BrandApartment();
		}
		
		// 设置集中式楼房列表信息
		List<Building> buildings = buildingService.searchBuilding();
		if(CollectionUtils.isNotEmpty(buildings)) {
			result.setBuildings(buildings);
		}
		return result;
	}
	
	/**
	 * 获取特定分辨率图片
	 * @param imgSrc
	 * @param resolution
	 * @return 图片路径
	 */
	public String getSmallImagePath(String imgSrc, String resolution) {
		Config config = Config.getInstance();
		String uploadRootPath = config.getUploadRootDir() + config.getUploadDir() + "BrandApartment" + "/";
		String oldImageSrc = config.getRealWebRootPath() + config.getSitePath()
				+ imgSrc;
		File roomAttachmentFile = new File(oldImageSrc);
		String attachmentFileName = roomAttachmentFile.getName();
		String newImageFile = resolution + "-" + attachmentFileName;
		String newImageSrc = config.getSitePath() + config.getUploadDir()
				+ "BrandApartment" + "/" + newImageFile;
		String newPath = uploadRootPath + newImageFile;
		File file = new File(newPath);
		if (!file.exists()) {
			String[] resString = resolution.split("x");
			if (roomAttachmentFile.exists()) {
				ImageUtils.zoomInImage(roomAttachmentFile, newPath,
						Integer.parseInt(resString[0]),
						Integer.parseInt(resString[1].toString()));
			} else {
				newImageSrc = null;
			}
		} else {
			
		}
		return newImageSrc;
	}
	
	/**
	 * 品牌公寓审核等状态修改
	 * @param model
	 */
	public void updateBrandApartmentStatus(BrandApartment model) {
		BrandApartment updateModel = genericService.load(model);
		updateModel.setStatus(model.getStatus());
		genericService.update(updateModel);
		
		// 更新BuildingInfo，将该房东对应的所有BuildingInfo更新
		buildingInfoService.updateBuildingInfoApartment(updateModel.getLandlordUser(), updateModel.getId(), updateModel.getBaName());
	}
	
	/**
	 * 定时器，更新品牌公寓的最低价格,和品牌公寓已发布房间数
	 */
	public void updateApartmentLowPrice() {
		BrandApartment model = new BrandApartment();
		model.setStatus(BrandApartment.STATUS_AUDITED);
		List<BrandApartment> brandApartments = genericService.searchAll(model).getData();
		if (CollectionUtils.isNotEmpty(brandApartments)) {
			for (BrandApartment brandApartment : brandApartments) {
				LandlordOwnerUser landlordUser = brandApartment.getLandlordUser();
				BigDecimal lowestPrice = roomInfoService.getLowestPriceOfRoom(landlordUser);
				Integer roomNum = buildingInfoService.getNumOfPublishRoom(brandApartment.getId());
				
				if (lowestPrice != null && !lowestPrice.equals(brandApartment.getLowPrice()) || roomNum > 0 && !roomNum.equals(brandApartment.getPublishRoomNum())) {
					brandApartment.setLowPrice(lowestPrice);
					brandApartment.setPublishRoomNum(roomNum);
					genericService.merge(brandApartment);
					logger.info("update brandApartment's lowest price and numbers of roomInfos!");
				}
			}
		}
		
		taskSchedulerService.updateTaskSchedulerRunTime(this.getClass(), "updateApartmentLowPrice");
	}
	
}
